package com.jielin.handling.service.user.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.bean.user.User;
import com.jielin.handling.bean.user.UserSearch;
import com.jielin.handling.mapper.user.UserMapper;
import com.jielin.handling.service.user.UserService;
import com.jielin.handling.util.StringUtil;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;
	
	@Override
	public void test() {
		log.info("service 测试成功");
		User user = userMapper.selectUserByOne();
		log.info("user:{}",JSONObject.toJSONString(user));
	}
	
	@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
	@Override
	public void testTransaction() {
		log.info("service 事务测试start...");
		try {
			User user = new User();
			user.setId(StringUtil.generatorUUID());
			user.setUsername("1");
			user.setPassword("1");
			user.setPhone("1");
			userMapper.insertUser(user);
			user.setId(StringUtil.generatorUUID());
			user.setUsername("2");
			user.setPassword("2");
			user.setPhone("2");
			userMapper.insertUser(user);
			user.setId(StringUtil.generatorUUID());
			user.setUsername("3");
			user.setPassword("3");
			user.setPhone("3");
			userMapper.insertUser(user);
		} catch (Exception e) {
			log.info("service 事务回滚:{}",e);
			//抛出异常让其回滚
			throw new RuntimeException("事务回滚");
		}
		log.info("service 事务测试end...");
	}
	
	@Override
	public long insertUser(User user) {
		user.setId(StringUtil.generatorUUID());
		log.info("user:{}",JSONObject.toJSONString(user));
		return userMapper.insertUser(user);
	}

	@Override
	public User getUserById(String id) {
		log.info("getUserById id:{}",id);
		return userMapper.selectUserById(id);
	}

	@Override
	public List<User> getUserList() {
		return userMapper.selectUserList();
	}

	@Override
	public List<User> getUserListByPage(UserSearch search) {
		List<User> list = null;
		try {
			PageHelper.startPage(search.getPageNum(), search.getPageSize());
			list = userMapper.selectUserListBySearch(search);
		} catch (Exception e) {
			log.error("查询异常={}",e);
		}
		return list;
	}

	@Override
	public User login(User user) {
		return userMapper.selectUserByLogin(user);
	}

}
